//
//  GrowthViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/3/31.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class GrowthViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,MWPhotoBrowserDelegate {
    
    var segmentedControl: UISegmentedControl!
    var tableView: UITableView!
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    var teacherArray = NSMutableArray()
    
    let top = 10
    var pageIndex = 1
    
    var photoArray = NSMutableArray()
    var apiurl = ""
    
    var hud: MBProgressHUD!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.title = "成长记录"
        
        InitViews()
        NotificationCenter.default.addObserver(self, selector: #selector(GrowthViewController.showBigImage(_:)), name: NSNotification.Name(rawValue: "showBigImage"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(GrowthViewController.shareNotification(_:)), name: NSNotification.Name(rawValue: "shareGrowNotification"), object: nil)
    }
    /**
     分享
     
     - parameter notification: 
     */
    func shareNotification(_ notification: Notification)  {
        
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let title = dic.object(forKey: "title") as! String
        let serid = dic.object(forKey: "serid") as! String
        let stuname = dic.object(forKey: "stuname") as! String
        let imageUrl = dic.object(forKey: "imageUrl") as! String
        var url = "\(server)/view/homework/apps/growshare.aspx?id=\(serid)"
        
        let user = getUserPojo()
        if self.apiurl.characters.count != 0 {
            url = url.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
        }
        
        let item1: ZYShareItem = ZYShareItem.init(title: "微信好友", icon: "wechat_L", handler: {
            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
            self.hud.animationType = MBProgressHUDAnimation.fade
            
            let queue = DispatchQueue(label: "queue")
            queue.async {
                print("分享到微信好友")
                let image = "\(server)\(imageUrl.components(separatedBy: "|")[0].replacingOccurrences(of: "../..", with: ""))"
                var data = try? Data.init(contentsOf: URL.init(string: image)!)
                if data == nil || data?.count == 0{
                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
                }
                
                UMSocialData.default().extConfig.wechatSessionData.url = url
                UMSocialData.default().extConfig.wechatSessionData.title = "［\(appname)］成长记录 \(stuname)"
                let urlResource = UMSocialUrlResource.init()
                urlResource.setResourceType(UMSocialUrlResourceTypeWeb, url: url)
                DispatchQueue.main.async(execute: { 
                    UMSocialDataService.default().postSNS(withTypes: [UMShareToWechatSession], content: title, image: data, location: nil, urlResource: urlResource, presentedController: self, completion: { (shareResponse) in
                        if shareResponse?.responseCode == UMSResponseCodeSuccess {
                            print("分享微信好友成功")
                        }
                        
                    })
                    self.hud.hide(true)
                })
                
            }
            
        })
        let item2: ZYShareItem = ZYShareItem.init(title: "朋友圈", icon: "wechat_moment_L", handler: {
            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
            self.hud.animationType = MBProgressHUDAnimation.fade
            let queue = DispatchQueue(label: "queue")
            queue.async {
                print("分享到微信朋友圈")
                let image = "\(server)\(imageUrl.components(separatedBy: "|")[0].replacingOccurrences(of: "../..", with: ""))"
                var data = try? Data.init(contentsOf: URL.init(string: image)!)
                if data == nil || data?.count == 0{
                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
                }
                UMSocialData.default().extConfig.wechatTimelineData.url = url
                let urlResource = UMSocialUrlResource.init()
                urlResource.setResourceType(UMSocialUrlResourceTypeWeb, url: url)
                DispatchQueue.main.async(execute: { 
                    UMSocialDataService.default().postSNS(withTypes: [UMShareToWechatTimeline], content: title, image: data, location: nil, urlResource: urlResource, presentedController: self, completion: { (shareResponse) in
                        if shareResponse?.responseCode == UMSResponseCodeSuccess {
                            print("分享微信朋友圈成功")
                        }
                        
                    })
                    self.hud.hide(true)
                })
                
            }
        })
//        let item3: ZYShareItem = ZYShareItem.init(title: "QQ好友", icon: "QQ_L", handler: {
//            
//            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
//            self.hud.animationType = MBProgressHUDAnimation.fade
//            let queue = DispatchQueue(label: "queue")
//            queue.async {
//                print("分享qq好友")
//                let image = "\(server)\(imageUrl.components(separatedBy: "|")[0].replacingOccurrences(of: "../..", with: ""))"
//                var data = try? Data.init(contentsOf: URL.init(string: image)!)
//                if data == nil || data?.count == 0{
//                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
//                }
//                UMSocialData.default().extConfig.qqData.title = "［桐乡教育］成长记录 \(stuname)"
//                UMSocialData.default().extConfig.qqData.url = url
//                DispatchQueue.main.async(execute: {
//                    UMSocialDataService.default().postSNS(withTypes: [UMShareToQQ], content: title, image: data, location: nil, urlResource: nil, presentedController: self, completion: { (shareResponse) in
//                        if shareResponse?.responseCode == UMSResponseCodeSuccess {
//                            print("分享qq成功")
//                        }
//                        self.hud.hide(true)
//                    })
//                })
//            }
//            
//        })
//        let item4: ZYShareItem = ZYShareItem.init(title: "QQ空间", icon: "qzone_L", handler: {
//            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
//            self.hud.animationType = MBProgressHUDAnimation.fade
//            let queue = DispatchQueue(label: "queue")
//            queue.async {
//                let image = "\(server)\(imageUrl.components(separatedBy: "|")[0].replacingOccurrences(of: "../..", with: ""))"
//                var data = try? Data.init(contentsOf: URL.init(string: image)!)
//                if data == nil || data?.count == 0{
//                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
//                }
//                UMSocialData.default().extConfig.qzoneData.title = "［桐乡教育］成长记录 \(stuname)"
//                UMSocialData.default().extConfig.qzoneData.url = url
//                DispatchQueue.main.async(execute: {
//                    UMSocialDataService.default().postSNS(withTypes: [UMShareToQzone], content: title, image: data, location: nil, urlResource: nil, presentedController: self, completion: { (shareResponse) in
//                        if shareResponse?.responseCode == UMSResponseCodeSuccess {
//                            print("分享qq空间成功")
//                        }
//                        self.hud.hide(true)
//                    })
//                })
//            }
//        })
//        let item5 = ZYShareItem.init(title: "新浪微博", icon: "sina_weibo_L", handler: {
//            
//            self.hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
//            self.hud.animationType = MBProgressHUDAnimation.Fade
//            dispatch_async(dispatch_get_global_queue(0, 0), {
//                
//                let image = "\(server)\(imageUrl.componentsSeparatedByString("|")[0].stringByReplacingOccurrencesOfString("../..", withString: ""))"
//                var data = NSData.init(contentsOfURL: NSURL.init(string: image)!)
//                if data == nil {
//                    data = UIImageJPEGRepresentation(UIImage.init(named: "appicon")! , 1.0)
//                }
//                UMSocialDataService.defaultDataService().postSNSWithTypes([UMShareToSina], content: title + url, image: data, location: nil, urlResource: nil, presentedController: self, completion: { (shareResponse) in
//                    if shareResponse.responseCode == UMSResponseCodeSuccess {
//                        print("分享新浪微博")
//                    }else{
//                        print(shareResponse.data)
//                    }
//                    self.hud.hide(true)
//                })
//            })
//        })
        let shareView = ZYShareView.init(shareItems: [item1,item2], functionItems: nil)
        shareView?.show()
    }
    
    /**
     显示大图
     
     - parameter notification:
     */
    func showBigImage(_ notification: Notification) {
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let imageUrl = dic.object(forKey: "url") as! String
        let index = UInt(dic.object(forKey: "index") as! String)
        let array = imageUrl.components(separatedBy: "|") as NSArray
        let array1 = NSMutableArray()
        array1.addObjects(from: array as [AnyObject])
        let n = array1.count
        photoArray = NSMutableArray()
        for i in 0...n-1 {
            var url = array1.object(at: i) as! String
            url = server + url.replacingOccurrences(of: "../..", with: "")

            let user = getUserPojo()
            if self.apiurl.characters.count != 0 {
                url = url.replacingOccurrences(of: server, with: user.doname).replacingOccurrences(of: "", with: "")
            }
            photoArray.add(MWPhoto.init(url: URL.init(string: url)))
            
        }
        let browser: MWPhotoBrowser = MWPhotoBrowser.init(delegate: self)
        // Set options
        browser.displayActionButton = true; // Show action button to allow sharing, copying, etc (defaults to YES)
        browser.displayNavArrows = false; // Whether to display left and right nav arrows on toolbar (defaults to NO)
        browser.displaySelectionButtons = false; // Whether selection buttons are shown on each image (defaults to NO)
        browser.zoomPhotosToFill = true; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
        browser.alwaysShowControls = false; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
        browser.enableGrid = true; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
        browser.startOnGrid = false; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
        browser.autoPlayOnAppear = false; // Auto-play first video
        
        // Customise selection images to change colours if required
        //        browser.customImageSelectedIconName = @"ImageSelected.png";
        //        browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
        //
        //        // Optionally set the current visible photo before displaying
        browser.setCurrentPhotoIndex(index!)
        self.navigationController?.pushViewController(browser, animated: true)
        browser.showNextPhoto(animated: true)
        browser.showPreviousPhoto(animated: true)
    }
    func numberOfPhotos(in photoBrowser: MWPhotoBrowser!) -> UInt {
        return UInt(photoArray.count)
    }
    func photoBrowser(_ photoBrowser: MWPhotoBrowser!, photoAt index: UInt) -> MWPhotoProtocol! {
        
        if index < UInt(photoArray.count) {
            
            return photoArray.object(at: Int(index)) as! MWPhotoProtocol
            
        }
        
        return nil;
    }
    
    func InitViews(){
        
        let array = ["全校纪录","班级排行","人员排行"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 30, y: 74, width: screenW - 60, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(ClassWorkViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)
        
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
        setUpRefresh()
        
    }
    func setUpRefresh() {
        if mark == "1" || mark == "3" {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(GrowthViewController.refresh))
            tableView.footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(GrowthViewController.loadMore))
            self.tableView.header.beginRefreshing()
        }else {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(GrowthViewController.refresh))
            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }
        
    }
    /**
     加载更多
     */
    func loadMore() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            var url = server + adminwebapppi
            if apiurl != "" {
                url = apiurl
            }
            pageIndex += 1
            let page: String = String(pageIndex)
            if mark == "1" {
                let request = requestHeader + "15</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
                workArray.addObjects(from: getData(url, request: request) as [AnyObject])
            }else if mark == "3" {
                let request = requestHeader + "17</t><sch>" + user.schid + "</sch><top>30</top><pagindex>" + page + "</pagindex></channel></rss>"
                
                teacherArray.addObjects(from: getData(url, request: request) as [AnyObject])
            }
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
 
        tableView.footer.endRefreshing()
    }
    /**
     刷新数据
     t=15   学校所有成长记录列表
     XmlNode schseridxml = ndoc.SelectSingleNode("//rss/channel/sch");
     XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
     XmlNode pagcountxml = ndoc.SelectSingleNode("//rss/channel/pagindex");
     
     t=17   学校成长记录 学生列表+数据
     XmlNode schseridxml = ndoc.SelectSingleNode("//rss/channel/sch");
     XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
     XmlNode pagcountxml = ndoc.SelectSingleNode("//rss/channel/pagindex");
     */
    func refresh() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            var url = server + adminwebapppi
            if apiurl != "" {
                url = apiurl
            }
            /**
             *  mark == "1" 全校记录
             *  mark == "2" 班级排行
             *  mark == "3" 人员排行
             */
            if mark == "1" {
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "15</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
                
                workArray = getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
            }else if mark == "2" {
                let request = requestHeader + "16</t><sch>" + user.schid + "</sch></channel></rss>"
                
                classArray = getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
            }else if mark == "3" {
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "17</t><sch>" + user.schid + "</sch><top>30</top><pagindex>" + page + "</pagindex></channel></rss>"
                
                teacherArray = getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
            }
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }

        tableView.header.endRefreshing()
    }
    /**
     选项切换
     */
    func selTab() {
        let n = segmentedControl.selectedSegmentIndex
        switch n {
        case 0:
            mark = "1"
            setUpRefresh()
            break
        case 1:
            mark = "2"
            setUpRefresh()
            break
        case 2:
            mark = "3"
            setUpRefresh()
            break
        default:
            break
        }
    }
    
    /**
     高度
     
     - parameter tableView: tableview
     - parameter indexPath: item
     
     - returns: 高度
     */
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            
            if (indexPath as NSIndexPath).row < workArray.count {
                let dic = workArray[indexPath.row] as! JSON
                
                var title = dic["title"].stringValue
                var content = dic["contents"].stringValue
                let imageUrl = dic["imgurl"].stringValue
                
                title = title.removingPercentEncoding!
                content = content.removingPercentEncoding!
                
                var height: CGFloat = 0.0
                if imageUrl.characters.count == 0 {
                    
                    height = 0.0
                    
                }else {
                    
                    let array = imageUrl.components(separatedBy: "|") as NSArray
                    
                    height = getPhotoCollectionHeight(array)
                }
                /// 头像，间隔，上下间隔，时间，图片等，内容
                let cellHeight: CGFloat = 20.0 + 50.0  + 30.0 + height + getLabelHeight(title, font: UIFont.systemFont(ofSize: 16) , wigth: screenW - 40) + getLabelHeight(content, font: UIFont.systemFont(ofSize: 14) , wigth: screenW - 40) + 5
                
                return cellHeight
            }else{
                return 0
            }
        }else if mark == "2" {
            return 60
        }else {
            return 60
        }
    }
    /**
     多少行
     
     - parameter tableView: tableview
     - parameter section:
     
     - returns: 行数
     */
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if mark == "1" {
            return workArray.count
        }else if mark == "2" {
            return classArray.count
        }else {
            return teacherArray.count
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if mark == "1" {
            
            if (indexPath as NSIndexPath).row < workArray.count {
                let cellIdentifier = "GrowthTableViewCellIdentifier";
                
                let dic = workArray[indexPath.row] as! JSON
                let cell = GrowthTableViewCell(dictionary: dic, apiUrl: apiurl, reuseIdentifier: cellIdentifier)
                cell.selectionStyle = UITableViewCellSelectionStyle.none;
                return cell
            }else{
                return UITableViewCell()
            }
            
            
        }else if mark == "2" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: ClassSendTableViewCell = ClassSendTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < classArray.count {
                let dic = classArray[indexPath.row] as! JSON
                let classname = dic["classname"].stringValue
                let count = dic["classcon"].stringValue
                
                cell.classname.text = classname
                cell.count.text = "发布：" + count
            }
            
            return cell
            
        }else {
            let cellIdentifier = "ClassCountTableViewCellIdentifier";
            
            let cell: StudentListTableViewCell = StudentListTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < teacherArray.count {
                let dic = teacherArray[indexPath.row] as! JSON
                let teaname = dic["stuname"].stringValue
                let count = dic["usersendcon"].stringValue
                var photo = dic["stuphoto"].stringValue
                photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
                photo = server + photo
                cell.userTx.sd_setImage(with: URL.init(string: photo), placeholderImage: UIImage.init(named: "touxiangm"))
                cell.userName.text = teaname
                cell.count.text = "发布：" + count
            }
            
            return cell
            
        }
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
